package controller

import (
	"bytes"
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/code128"
	"github.com/gin-gonic/gin"
	"image/png"
	"net/http"
)

func BarcodePage(c *gin.Context) {
	c.HTML(http.StatusOK, "barcode.html", gin.H{})
}

func GenerateBarcode(c *gin.Context) {
	text := c.Query("text")
	cs, err := code128.Encode(text)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}
	barCode, err := barcode.Scale(cs, 350, 70)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}
	buf := new(bytes.Buffer)
	err = png.Encode(buf, barCode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}
	c.Data(http.StatusOK, "image/png", buf.Bytes())
}
